#include "LayerPanel.h"
#include "AlgebraicSum.h"
#include "AlgebraicDifference.h"
#include "AlgebraicProduction.h"



LayerPanel::LayerPanel(QWidget *parent)
: QWidget(parent), _pWork (NULL)
{
	ui.setupUi(this);
	_layerModes.push_back (new AlgebraicOperation ());
	_layerModes.push_back (new AlgebraicSum ());
	_layerModes.push_back (new AlgebraicDifference ());
	_layerModes.push_back (new AlgebraicProduction ());
	for (int i = 0; i < _layerModes.size (); ++i)
		ui.cbLayerMode->addItem (_layerModes[i]->getOperationName ());
	ui.cbLayerMode->setEnabled (false);
}




LayerPanel::~LayerPanel ()
{

}




void LayerPanel::setWork (Ptr< Work > pWork)
{
	if (_pWork != NULL) {
		for (int i = 0; i < _layerItems.size (); ++i) {
			LayerItem * pLayerItem = _layerItems[i];
			ui.verticalLayout_2->removeWidget (pLayerItem);
			pLayerItem->deleteLater ();
		}
		_layerItems.clear ();
	}
	if (pWork == NULL) {
		ui.cbLayerMode->setEnabled (false);
		return;
	}
	_pWork = pWork;
	Ptr< Document > pDoc = _pWork->getDoc ();
	for (int i = 0; i < pDoc->getLayerCount (); ++i) {
		LayerItem * pNewLayerItem = new LayerItem (this, 
				pDoc->getLayer (i), i);
		connect (pNewLayerItem, SIGNAL(select(int)), this, 
				SLOT(selectLayer (int)));
		ui.verticalLayout_2->addWidget (pNewLayerItem);
		_layerItems.push_back (pNewLayerItem);
		if (pDoc->getLayer (i) == pDoc->getCurrentLayer ()) {
			pNewLayerItem->setChecked (true);
			for (int j = 0; j < _layerModes.size (); ++j) {
				if (_layerModes[j]->getOperationName () == pDoc
					->getCurrentLayer ()->getCompositionOperation ()
					->getOperationName ())
					ui.cbLayerMode->setCurrentIndex (j);
			}
		} else
			pNewLayerItem->setChecked (false);
	}
	ui.cbLayerMode->setEnabled (true);
}

void LayerPanel::selectLayer (int index)
{
	for (int i = 0; i < _layerItems.size (); ++i) {
		if (i != index)
			_layerItems[i]->setChecked (false);
		else
			_layerItems[i]->setChecked (true);
	}
	_pWork->getDoc ()->setCurrentLayer (index);
	for (int j = 0; j < _layerModes.size (); ++j) {
		if (_layerModes[j]->getOperationName () == _pWork->getDoc ()
				->getCurrentLayer ()->getCompositionOperation ()
				->getOperationName ())
			ui.cbLayerMode->setCurrentIndex (j);
	}
}

void LayerPanel::selectMode (int modeIndex)
{
	if (_pWork == NULL)
		return;
	_pWork->getDoc ()->getCurrentLayer ()->setCompositionOperation (
			_layerModes[modeIndex]);
	_pWork->getDoc ()->refreshCompositedImage ();
	_pWork->getViewportUI ()->repaint ();
}

